<template>
  <div class="weChatAddWarp">
    <div class="first-step" v-show="currentStep === 'first'">
      <div class="wechat-icon">
        <img src="../../../../../assets/img/wechat_mini_logo.png" alt="">
      </div>
      <h3>{{$t('configLazyLoad.channel.wexinAPPTip17')}}</h3>
      <div class="wechatType">
        <div class="wechatType_warp">
          <div class="wechatoption" style="margin-right: 30px">
            <el-radio label="wechatApp" v-model="choosewechatType" class="font18">{{$t('configLazyLoad.channel.wexinAPPTip5')}}</el-radio>
            <p>{{$t('configLazyLoad.channel.wexinAPPTip18')}}</p>
          </div>
          <div class="wechatoption">
            <el-radio label="wechaH5" v-model="choosewechatType" disabled class="font18">{{$t('configLazyLoad.channel.wexinAPPTip19')}}</el-radio>
            <p style="color: #f56c6c">{{$t('configLazyLoad.channel.wexinAPPTip20')}}</p>
            <!--<p>适用于小程序嵌入H5界面聊天框</p>-->
          </div>
        </div>
      </div>
      <div class="btn">
        <el-button class="primary_btn" style="margin-right: 20px" @click="cancelType">{{$t('public.cancel')}}</el-button>
        <el-button type="primary" class="primary_btn" @click="nextStep(1)">{{$t('public.confirm')}}</el-button>
      </div>
      <div class="remark">
        {{$t('configLazyLoad.channel.wexinAPPTip21')}}</br>
        {{$t('configLazyLoad.channel.wexinAPPTip021')}}</br>
        {{$t('configLazyLoad.channel.wexinAPPTip0021')}}</br>
        {{$t('configLazyLoad.channel.wexinAPPTip00021')}}</br>
        {{$t('configLazyLoad.channel.wexinAPPTip000021')}}</br>
      </div>
    </div>

    <div class="second-step"  v-show="currentStep === 'second'">
      <div class="title">{{$t('configLazyLoad.channel.wexinAPPTip22')}}</div>
      <el-form ref="ruleForm" :rules="rules" :model="form" :label-position="'left'"  label-width="210px">
        <el-form-item :label="$t('configLazyLoad.channel.appletName')" prop="name">
          <el-input v-model.trim="form.name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('configLazyLoad.channel.wexinAPPTip12')" prop="appid">
          <el-input v-model.trim="form.appid"></el-input>
        </el-form-item>
        <el-form-item :label="$t('configLazyLoad.channel.wexinAPPTip13')" prop="appSecret">
          <el-input v-model.trim="form.appSecret" ></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="22">
            <el-form-item :label="$t('configLazyLoad.channel.wexinAPPTip14')" prop="access_token_url">
              <el-input v-model.trim="form.access_token_url"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="ques" :span="2">
            <question-tooltip class="wechatTootip" :direction="'bottom'" :tipContent="$t('configLazyLoad.channel.wexinAPPTip15')"></question-tooltip>
          </el-col>
        </el-row>
        <el-form-item :label="$t('configLazyLoad.channel.useSche')" prop="scheduleEnable" v-show="configType === 'config'">
          <el-radio-group v-model.trim="form.scheduleEnable">
            <el-radio :label="true">{{$t('configLazyLoad.public.reuse')}}</el-radio>
            <el-radio :label="false">{{$t('configLazyLoad.public.noReuse')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <p class="remark" style="padding-left: 0px">{{$t('configLazyLoad.channel.wexinTip23')}}</p>
        <el-form-item v-show="!form.scheduleEnable" :label="$t('configLazyLoad.interfaceConfig.msgGroup')" prop="to_peer">
          <el-select size="mini" v-model.trim="form.to_peer" :placeholder="$t('public.pleasePick')">
            <el-option
              v-for="(item, index) in peerOptions"
              :key="index"
              :label="item.DisplayName"
              :value="item.Exten"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="!form.scheduleEnable"  :label="$t('config.channel.isUseRobt')" prop="robot">
          <el-select size="mini" v-model.trim="form.robot" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
            <el-option value="">{{$t('public.pleasePick')}}</el-option>
            <el-option
              v-for="item in allrobotOptions"
              :key="item._id"
              :label="item.robot_name_new"
              :disabled="item.disabled"
              :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-show="!form.scheduleEnable && aiRobots.length > 0"  :label="$t('configLazyLoad.channel.robotAssistId')" prop="robotAssistId">
          <el-select size="mini" v-model.trim="form.robotAssistId" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
            <el-option value="">{{$t('public.pleasePick')}}</el-option>
            <el-option
              v-for="item in aiRobots"
              :key="item._id"
              :label="item.robot_name_new"
              :disabled="item.disabled"
              :value="item._id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-row>
          <el-col :span="22">
            <el-form-item :label="$t('configLazyLoad.channel.turnTip3')">
              <el-radio-group v-model.trim="form.openTriggerWord">
                <el-radio :label="false">{{$t('public.no')}}</el-radio>
                <el-radio :label="true">{{$t('public.yes')}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col class="ques" :span="2">
            <question-tooltip class="wechatTootip" :direction="'bottom'" :tipContent="$t('configLazyLoad.channel.turnTip4')"></question-tooltip>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="22">
            <el-form-item :label="$t('config.channel.userPeopleWord')" prop="convert_words">
              <el-input size="mini" v-model.trim="form.convert_words" :placeholder="$t('configLazyLoad.channel.turnTip5')"></el-input>
            </el-form-item>
          </el-col>
          <el-col class="ques" :span="2">
            <question-tooltip class="wechatTootip" :direction="'bottom'" :tipContent="$t('configLazyLoad.channel.turnTip6')"></question-tooltip>
          </el-col>
        </el-row>
        <el-form-item v-show="!form.scheduleEnable" :label="$t('config.channel.sendWelcomeMsg')" prop="welcomePushTime">
          <el-radio-group v-model="form.welcomePushTime" @change="pushTimeChange">
            <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
            <el-radio class="radio welcome-radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="!form.scheduleEnable"  :label="$t('config.channel.welcomeMsg')" prop="welcome_msg">
          <span class="remark">{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
          <question-tooltip
                  class="weiboTooltip"
                  :direction="'bottom'"
                  :tipContent="$t('configLazyLoad.channel.webStyleTip6')">
          </question-tooltip>
          <div class="placeholder_box">
            <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
              {{place.content}}
              <i class="iconfont icon-zhankai"></i>
            </dl>
          </div>
          <el-input size="mini" type="textarea" v-model="form.welcome_msg"></el-input>
        </el-form-item>
        <el-form-item :label="$t('config.channel.isUseSatisfaction')" prop="csr">
          <el-radio class="radio" v-model.trim="form.webchat_csr" :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
          <el-radio class="radio statis-radio" v-model.trim="form.webchat_csr" :label="true">{{$t('config.channel.enabled')}}</el-radio>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="primary_btn fr" @click="nextStep(2)">{{$t('public.nextStep')}}</el-button>
          <el-button class="primary_btn fr" style="margin-right: 20px" @click="cancelType">{{$t('public.cancel')}}</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="last-step" v-show="currentStep === 'last'">
      <el-form :model="form" :label-position="'left'" label-width="120px">
        <div class="step-title">{{$t('configLazyLoad.channel.wexinAPPTip23')}}</div>
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item :label="$t('configLazyLoad.channel.wexinTip104')" prop="server_url">
              <el-input v-model.trim="form.server_url" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-tooltip :content="$t('public.copy')" placement="bottom">
              <i class="quickRe iconfont icon-fuzhi" @click="copy('server_url')"></i>
            </el-tooltip>
          </el-col>
        </el-row>
        <div class="step-title">
          {{$t('configLazyLoad.channel.wexinAPPTip24')}}
        </div>
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item :label="$t('configLazyLoad.channel.wexinTip106')" prop="token">
              <el-input v-model.trim="form.token" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-tooltip :content="$t('public.copy')" placement="bottom">
              <i class="quickRe iconfont icon-fuzhi" @click="copy('token')"></i>
            </el-tooltip>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="22">
            <el-form-item label="EncodingAESKey：" prop="encoding_AESKey">
              <el-input v-model.trim="form.encoding_AESKey" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2">
            <el-tooltip :content="$t('public.copy')" placement="bottom">
              <i class="quickRe iconfont icon-fuzhi" @click="copy('encoding_AESKey')"></i>
            </el-tooltip>
          </el-col>
        </el-row>

        <div class="step-title">
          {{$t('configLazyLoad.channel.wexinAPPTip25')}}
        </div>
        <div class="step-title">
         {{$t('configLazyLoad.channel.wexinAPPTip26')}}
        </div>
        <div class="tips" style="color: #3b5998;    margin-bottom: 20px;">
          {{$t('configLazyLoad.channel.wexinAPPTip27')}}
        </div>
        <el-form-item>
          <el-button type="primary" class="primary_btn fr" @click="onSubmit">{{$t('public.save')}}</el-button>
          <el-button class="primary_btn fr" style="margin-right: 20px" @click="previousStep">{{$t('config.channel.prevStep')}}</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
  import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  import Clipboard from 'clipboard-js'
  import { randomWord, deepClone } from '@/utils/m7Utils'
  export default {
    name: '',
    props: {
      wechatUrl: String
    },
    data () {
      return {
        choosewechatType: 'wechatApp',
        form: {
          _id: '',
          name: '',
          appid: '',
          appSecret: '',
          access_token_url: '',
          webchat_csr: false,
          welcomePushTime: 'access',
          welcome_msg: '',
          convert_words: '',
          robot: '',
          encoding_AESKey: '',
          token: '',
          to_peer: '',
          server_url: '',
          openTriggerWord: true,
          scheduleEnable: false
        },
        peerOptions: [],
        robotOptions: [],
        aiRobots: [],
        allrobotOptions: [],
        placeholderArr: [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ],
        rules: {
          name: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ],
          appid: [
            { required: true, message: this.$t('validate.required'), trigger: 'blur' }
          ]
        },
        currentStep: 'second'
      }
    },
    components: {
      questionTooltip
    },
    computed: {
      configType () {
        let paths = this.$route.path.split('/')
        return paths[2]
      }
    },
    methods: {
      robotSelectShow (show) {
        if (show) {
          this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
            if (res2 && res2.success && res2.data && res2.data.length > 0) {
              let aiRobot = res2.data
              let allRobot = this.allrobotOptions
              aiRobot.forEach((item1) => {
                item1._id = item1.Id
                item1.robot_name_new = item1.Nick
                let exist = allRobot.findIndex((all) => {
                  return all.Id === item1.Id
                })
                if (exist === undefined) {
                  allRobot.push(item1)
                } else {
                  allRobot.splice(exist, 1, item1)
                }
              })
              this.aiRobots = aiRobot
              this.allrobotOptions = allRobot
            }
          })
        }
      },
      nextStep (step) {
        if (step === 1) {
          if (this.choosewechatType === 'wechaH5') {
            this.$emit('addWechaH5')
            return
          }
          this.currentStep = 'second'
        } else if (step === 2) {
          if (this.peerOptions.length === 0) {
            this.$message.error(this.$t('configLazyLoad.channel.robotError4'))
            return
          }
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              let data = this.form
              if (!data.scheduleEnable) {
                if (!data.to_peer) {
                  this.$message.error(this.$t('webchat.placeSkillsGrouop'))
                  return
                }
              }
              if (!data.appSecret && !data.access_token_url) {
                this.$message.error(this.$t('configLazyLoad.channel.wexinAPPTip16'))
                return
              }
              this.form.server_url = this.wechatUrl + '/wxmini/' + this.form.appid
              this.form.encoding_AESKey = randomWord(false, 43)
              this.form.token = randomWord(false, 32)
              this.currentStep = 'last'
            }
          })
        }
      },
      previousStep () {
        this.currentStep = 'second'
      },
      addPlaceholder (data) {
        this.form.welcome_msg += '{' + data + '}'
      },
      cancelType () {
        this.$emit('cancle')
      },
      //  更改欢迎语推送时机
      pushTimeChange (data) {
        if (data === 'access') {
          this.placeholderArr = [
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }
          ]
          let str = deepClone(this.form.welcome_msg)
          str = str.replace(/\{agent\}/g, '')
          str = str.replace(/\{agentName\}/g, '')
          this.form.welcome_msg = str
        } else if (data === 'claim') {
          this.placeholderArr = [
            {
              content: this.$t('configLazyLoad.channel.nickName'),
              data: 'nickName'
            }, {
              content: this.$t('configLazyLoad.channel.agent'),
              data: 'agent'
            }, {
              content: this.$t('configLazyLoad.channel.agentName'),
              data: 'agentName'
            }, {
              content: this.$t('configLazyLoad.channel.agentNickName'),
              data: 'agentNickName'
            }, {
              content: this.$t('configLazyLoad.channel.agentPhone'),
              data: 'agentPhone'
            }
          ]
        }
      },
      onSubmit () {
        this.$refs.ruleForm.validate((valid) => {
          if (valid) {
            let data = this.form
            if (!data.appSecret && !data.access_token_url) {
              this.$message.error(this.$t('configLazyLoad.channel.wexinAPPTip16'))
              return
            }
            if (!data.scheduleEnable) {
              if (data.robot === '') {
                data.robotType = ''
              } else {
                this.allrobotOptions.forEach((item) => {
                  if (item._id === data.robot) {
                    if (item.Nick) {
                      data.robotType = item.robotType
                    } else {
                      data.robotType = item.robot_type_new
                    }
                  }
                })
              }
              //          机器人辅助座席，增加assistRobotType参数
              this.aiRobots.map((item) => {
                if (data.robotAssistId === item._id) {
                  if (data.robotAssistId !== '') {
                    this.$set(data, 'assistRobotType', item.robotType)
                  } else {
                    this.$set(data, 'assistRobotType', '')
                  }
                }
              })
              data.robot = data.robot ? data.robot : ''
            }
            data._id = data.appid
            this.$store.dispatch('saveWeixinMiniConfig', data).then((req) => {
              if (req.success) {
                this.$message.success(this.$t('configLazyLoad.channel.mailTip36'))
                this.$emit('submitEditOrAdd')
              }
            })
          }
        })
      },
      copy (type) {
        let self = this
        Clipboard.copy(this.form[type]).then(
          function () {
            self.$message.success(this.$t('config.business.copySuccess'))
          }
        )
      }
    },
    mounted () {
      this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
        let mailQueues = this.$getCache('mailQueues')
        if (!mailQueues || mailQueues.length === 0) {
          return
        }
        this.peerOptions = mailQueues || []
      })
      this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
        let robotConfig = this.$getCache('robotConfig')
        this.robotOptions = robotConfig || []
        this.allrobotOptions = this.robotOptions
        this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
          if (res2 && res2.success && res2.data && res2.data.length > 0) {
            let aiRobot = res2.data
            aiRobot.forEach((item1) => {
              item1._id = item1.Id
              item1.robot_name_new = item1.Nick
            })
            this.aiRobots = aiRobot
            let configArr = []
            this.allrobotOptions.forEach((config) => {
              if (config.robot_type !== 'didi') {
                configArr.push(config)
              }
            })
            this.allrobotOptions = configArr.concat(this.aiRobots)
          }
        })
      })
      // 判断小七是否回显
      if (this.$store.state.isM7RobotOpen === false) {
        if (this.form.robot === '5825a500dfe52d5edc6e36c9') {
          this.form.robot = ''
        }
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .wechat-icon
    text-align center
  .weChatAddWarp
    padding 20px
  .remark
    color #3b5998
    padding-left 20px
  .wechatType
    padding 20px
    text-align: center
    overflow: hidden
    .wechatType_warp
      margin 0 auto
      width: 285px
      overflow: hidden
    .wechatoption
      text-align left
      width 125px
      display inline-block
      float left
      p
        color $cf-gray4
        padding-left 20px
  .first-step
    h3
      font-size 18px
      text-align center
      margin-top 30px
    .btn
      margin 20px
      text-align center
  .second-step
    .ques
      line-height 40px
      padding-left 10px
    .title
      font-size 16px
      margin 20px 0
  .step-title
    font-size 18px
    line-height 30px
    margin-bottom 20px
  .last-step
    .el-form-item
      padding-left 33px
    .el-row
      margin-bottom 20px
    .el-col-2
      line-height 30px
      color $c-main
      cursor pointer
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height:16px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
</style>
